package cn.ctyun.ipush.utils;

import cn.ctyun.ipush.model.EmailModel;
import cn.ctyun.ipush.model.EtlMailManager;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.validator.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-7-4
 * Time: 上午9:28
 * To change this template use File | Settings | File Templates.
 */
public class EmailUtils {


    /* 日志对象 */
    private static final Logger LOG = LoggerFactory.getLogger(EmailUtils.class);

    public static boolean startMailSendTask(EmailModel emailModel) throws Exception {

        EtlMailManager etlMailManager = new EtlMailManager();

        etlMailManager.setToList(emailModel.getEmailReceiversDb());//接收人
        //etlMailManager.setCcList("18133847059@189.cn");
        etlMailManager.setSubject(emailModel.getEmailSubject());
        if(StringUtils.isEmpty(emailModel.getEmailContent())){
            etlMailManager.setMessage("请查收");
        }else{
            etlMailManager.setMessage(emailModel.getEmailContent());
        }

        etlMailManager.setAttachments(emailModel.getAttachmentList());
        if(etlMailManager.getAttachments()==null){
            etlMailManager.setAttachments("D:/ipush/邮件报表测试请忽略.xlsx");
        }

        if (null != emailModel && !emailModel.getEmailModelId().isEmpty()) {
            HtmlEmail email = null;
            List<MimeBodyPart> attachmentList = new ArrayList<MimeBodyPart>();
            List<String> emailReceiverList = new ArrayList<String>();
            List<String> emailCCList = new ArrayList<String>();
            //初始化邮件信息
            initEmailInfo(email, attachmentList, emailReceiverList, emailCCList, etlMailManager);
            //发送邮件
            if(!sendMail(email, etlMailManager.getSubject(), etlMailManager.getMessage(), attachmentList, emailReceiverList, emailCCList, emailModel))
                return false;
        } else {
            LOG.error("邮件发送任务不存在，请核查！");
            return false;
        }
        return true;
    }

    public static boolean sendMail( HtmlEmail email,  String subject,  String message,  List<MimeBodyPart> attachmentList,
                                    List<String> emailReceiverList,  List<String> emailCCList,  EmailModel emailModel) {
        try {
            HtmlEmail emailSender = email;
            if (null == emailSender) {
                emailSender = new HtmlEmail();
                try {
                    // email.setDebug(true);
                    emailSender.setCharset("UTF-8");
                    emailSender.setHostName(emailModel.getSmtpServer());
                    emailSender.setSmtpPort(Integer.parseInt(emailModel.getSmtpPort()));
                    emailSender.setAuthentication(emailModel.getSmtpUser(), DataUtils.decodeString(emailModel.getSmtpPassword()));
                    emailSender.setFrom(emailModel.getEmailSender(), emailModel.getEmailSender());//设置邮件发送人
                } catch (EmailException e) {
                    LOG.error("Set Mail Properties Error:" + e.getMessage());
                    return false;
                }catch (IOException ex){
                    LOG.error("Set Mail Properties Error:" + ex.getMessage());
                    return false;
                }
            }
            try {
                MimeMultipart msgMultipart = new MimeMultipart("mixed");
                emailSender.setContent(msgMultipart);
                if (attachmentList != null && !attachmentList.isEmpty()) {
                    for (MimeBodyPart attachment : attachmentList) {
                        msgMultipart.addBodyPart(attachment);
                    }
                    emailSender.addPart(msgMultipart);
                }
            } catch (Exception e) {
                LOG.error("Set Mail attachment Error:" + e.getMessage());
                return false;
            }
            emailSender.setSubject(subject==null?" ":subject);
            emailSender.setMsg(message==null?"  ":message);
            for (String toMail : emailReceiverList) {
                if (EmailValidator.getInstance().isValid(toMail)) {
                    emailSender.addTo(toMail);
                }
            }
            if (CollectionUtils.isNotEmpty(emailCCList)) {
                for (String ccMail : emailCCList) {
                    if (EmailValidator.getInstance().isValid(ccMail)) {
                        emailSender.addCc(ccMail);
                    }
                }
            }

            String result = emailSender.send();
        } catch (EmailException e) {
            LOG.error("Send mail error: " + e.getMessage());
            return false;
        }
        return true;
    }

    private static void initEmailInfo(HtmlEmail email, List<MimeBodyPart> attachmentList, List<String> emailReceiverList, List<String> emailCCList, EtlMailManager etlMailManager) throws Exception {

        // 初始化收件人
        if (StringUtils.isEmpty(etlMailManager.getToList())) {
            LOG.error("无收件人，请核查！");
            return;
        } else {
            emailReceiverList.addAll(strToList(etlMailManager.getToList(), "\\$"));
        }

        //初始化抄送人
        if (!StringUtils.isEmpty(etlMailManager.getCcList())) {
            emailCCList.addAll(strToList(etlMailManager.getCcList(), "\\$"));
        }

        //初始化附件
        if (!StringUtils.isEmpty(etlMailManager.getAttachments())) {
            List<String> attachmentPathList = strToList(etlMailManager.getAttachments(), "\\$");

            for (String attachmentPath : attachmentPathList) {
//                String sourceStr = "excel/outfiles" + attachmentStr;
//              ServletContext sc = request.getSession().getServletContext();
//              String template_file_path = sc.getRealPath(TEMPLATE_FILE_PATH_PART);
                //String basePath="excel/outfiles/";
                //URL url = Thread.currentThread().getContextClassLoader().getResource(attachmentPath);
                File file = new File(attachmentPath);
                try{
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataSource ds1 = new FileDataSource(file);
                    DataHandler dh1 = new DataHandler(ds1);
                    attachment.setDataHandler(dh1);
                    attachment.setFileName(MimeUtility.encodeWord(file.getName(), "GBK", null));
                    attachmentList.add(attachment);
                }catch (Exception ex){
                    LOG.error("附件下载失败: " + file.getName());
                }
            }
        }
    }

    private static List<String> strToList(String srcStr, String regex) {
        Pattern pattern = Pattern.compile(regex);
        String[] strings = pattern.split(srcStr);
        return java.util.Arrays.asList(strings);
    }
}
